package yxy.apple.util.data;

import org.redisson.api.RMap;

import yxy.apple.util.redisson.RedisConnection;
import yxy.apple.util.redisson.RedisException;

public abstract class RedisContainer extends DataContainer {

	private RedisConnection redis = null;

	public RedisContainer(RedisConnection redis) {
		this.redis = redis;
	}

	protected RedisConnection redis() {
		return this.redis;
	}

	public static boolean exists(RedisConnection redis, String tag) throws Exception {
		return RedisContainer.map(redis, tag).isExists();
	}

	private static RMap<String, Object> map(RedisConnection redis, String name) throws RedisException {
		if (redis != null && redis.ready()) {
			return redis.client().getMap(name);
		} else {
			throw new RedisException("无可用Redis连接！");
		}
	}

	protected RMap<String, Object> map() throws RedisException {
		String tag = this.tag();
		return RedisContainer.map(this.redis, tag);
	}

	@Override
	public void put(String key, Object value) {
		try {
			RMap<String, Object> map = this.map();
			map.fastPut(key, value);
		} catch (Exception e) {
			this.thrown(e);
		}
	}

	public <T> T get(String key, T defaultValue) {
		try {
			String tag = this.tag();
			RMap<String, T> map = this.redis.client().getMap(tag);
			return map.get(key);
		} catch (Exception e) {
			this.thrown(e);
			return defaultValue;
		}
	}

	@Override
	public Object get(String key) {
		try {
			String tag = this.tag();
			RMap<String, Object> map = this.redis.client().getMap(tag);
			return map.get(key);
		} catch (Exception e) {
			this.thrown(e);
			return null;
		}
	}

	@Override
	public Object remove(String key) {
		try {
			String tag = this.tag();
			RMap<String, Object> map = this.redis.client().getMap(tag);
			return map.remove(key);
		} catch (Exception e) {
			this.thrown(e);
			return null;
		}
	}

	/**
	 * 在Redis中作为Map存储时使用的标签
	 * 
	 * @return
	 */
	protected abstract String tag();

	/**
	 * 出现异常时回调
	 * 
	 * @param cause
	 */
	protected abstract void thrown(Throwable cause);
}
